/*
 * @Description: 
 * @Author: paddies
 * @Date: 2024-11-06 12:51:29
 * @LastEditors: paddies
 * @LastEditTime: 2025-09-30 02:57:23
 * @FilePath: /shared_components/lib/luntai-components/build-deliver-goods/buildDeliverGoods.dart
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
// import 'package:fluttercli/components/Fun/fun.dart';
import 'package:shared_components/build-button/buildButton.dart';
import 'package:shared_components/build-common/buildCommon.dart';
import 'package:shared_components/build-image/buildImage.dart';
import 'package:shared_components/build-input/buildInput.dart';
import 'package:shared_components/build-radio-group/buildRadioGroup.dart';
import 'package:shared_components/build-radio/buildRadio.dart';
import 'package:shared_components/build-select/buildSelect.dart';

//输入框控制器
TextEditingController logisticCompanyController = TextEditingController();
TextEditingController driverPhoneController = TextEditingController();
TextEditingController logisticNumberController = TextEditingController();
TextEditingController carNumberController = TextEditingController();

buildDeliverGoods(
    {dynamic item,
    List<dynamic> logisticCompanyList = const [],
    Function? onRefresh,
    String? type,
    Function? doUpdatelogistic}) {
  // var logisticCompanyList = [].obs;
  var goodsList = [].obs;
  var logisticCompanySn = [].obs;
  var logisticNumber = "".obs;
  var remark = "".obs;
  var tireSize = "".obs;
  var logisticCompany = "".obs;
  var deliverType = "".obs;
  var screenBottomHeight = MediaQuery.of(Get.overlayContext!).padding.top;
  var newLogisticsCompany = "".obs;

  var carNumber = "".obs; //送货车牌
  var driverName = "".obs; //送货司机
  var driverPhone = "".obs; //司机电话
  if (item["orderItems"] != null) {
    print("真的有goodsList===");
    print(item["orderItems"] ?? []);
    goodsList.value = item["orderItems"] ?? [];
  }
  //根据配件处理
  var newList = [].obs;
  for (var i = 0; i < goodsList.length; i++) {
    var data = goodsList[i] as Map<String, dynamic>;
    var n = int.parse(showText(data["quantity"]));
    var tire = [];
    for (var j = 0; j < n; j++) {
      tire.add("");
    }
    newList.value.add({...data, "tire": tire});
  }
  print("内容数据=====");
  print(item);
  print(item["attrVo"]);
  var attrVoList = [].obs;
  if (item["attrVo"] != null) {
    attrVoList.value = item["attrVo"] ?? [];
  }

  // double.parse(GlobalPrefs.getValue("screenBottomHeight"));

  var quantity = int.parse(showText(item["quantity"]) ?? "0");
  var tireSizes = [].obs;
  for (var i = 0; i < quantity; i++) {
    tireSizes.value.add("");
  }
  Get.bottomSheet(
      isScrollControlled: true,
      Container(
          padding: EdgeInsets.only(left: 10, right: 10, top: 20),
          decoration: new BoxDecoration(
            color: Colors.white,
            // new Radius.circular(20.0)
            borderRadius: new BorderRadius.only(
                topLeft: new Radius.circular(20.0),
                topRight: new Radius.circular(20.0)), //圆角
          ),
          height: 600,
          child: Obx(() => Container(
              width: double.infinity,
              height: double.infinity,
              // color: Colors.red,
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    alignment: Alignment.center,
                    child: Text(
                      "发货",
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Expanded(
                      child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    child: SingleChildScrollView(
                        child: Column(
                      children: [
                        buildRadio(
                            required: true,
                            title: "配送方式",
                            value: deliverType.value,
                            widthFactor: 1,
                            list: [
                              // ...judgeIdList.value
                              {"label": "自配", "value": "0"},
                              {"label": "物流", "value": "1"},
                            ],
                            onChanged: (v) {
                              deliverType.value = v;
                              driverPhone.value = "";
                              driverPhoneController.text = "";
                              logisticCompany.value = "";
                              logisticCompanyController.text = "";
                              // judgeId.value = v;
                              // handleResultId.value = [];
                              // resetInput();
                            }),
                        Visibility(
                            visible: deliverType.value == '1',
                            child: buildInput(
                                required: true,
                                title: "物流公司",
                                value: logisticCompany.value,
                                unit: "历史",
                                textEditingController:
                                    logisticCompanyController,
                                unitSolt: buildButton(
                                    title: "历史",
                                    fontSize: 14,
                                    borderRadius: 2,
                                    onClick: () {
                                      Get.toNamed("/searchLogisticsCompany",
                                          arguments: {
                                            "name": logisticCompany.value
                                          })?.then((value) {
                                        if (value != null) {
                                          logisticCompany.value =
                                              showText(value["companyName"]);
                                          driverPhone.value =
                                              showText(value["phone"]);

                                          logisticCompanyController.text =
                                              logisticCompany.value;
                                          driverPhoneController.text =
                                              driverPhone.value;
                                        }
                                      });
                                    },
                                    colors: [
                                      Color(0xff0101ea),
                                      Color(0xff0101ea)
                                    ]),
                                onChanged: (v) {
                                  logisticCompany.value = v;
                                })),
                        // Visibility(
                        //   visible: deliverType.value == '1',
                        //   child: buildSelect(
                        //       required: true,
                        //       title: "物流公司",
                        //       canInput: true,
                        //       value: logisticCompanySn.value,
                        //       onChanged: (v, n) {
                        //         newLogisticsCompany.value = n;
                        //         logisticCompanySn.value = v;
                        //         logisticCompany.value = n;
                        //       },
                        //       multiple: false,
                        //       list: logisticCompanyList),
                        // ),
                        Visibility(
                            visible: deliverType.value == '1',
                            child: buildInput(
                                required: true,
                                title: "物流单号",
                                value: logisticNumber.value,
                                textEditingController: logisticNumberController,
                                onChanged: (v) {
                                  logisticNumber.value = v;
                                })),
                        Visibility(
                            visible: deliverType.value == '1',
                            child: buildInput(
                                required: true,
                                title: "物流电话",
                                value: driverPhone.value,
                                textEditingController: driverPhoneController,
                                onChanged: (v) {
                                  driverPhone.value = v;
                                })),

                        Visibility(
                            visible: deliverType.value == '0',
                            child: buildInput(
                                required: true,
                                title: "送货车牌",
                                unit: "历史",
                                textEditingController: carNumberController,
                                unitSolt: buildButton(
                                    title: "历史",
                                    fontSize: 14,
                                    borderRadius: 2,
                                    onClick: () {
                                      Get.toNamed("/searchCarCompany",
                                          arguments: {
                                            "name": logisticCompany.value
                                          })?.then((value) {
                                        if (value != null) {
                                          carNumber.value =
                                              showText(value["carNumber"]);
                                          carNumberController.text =
                                              carNumber.value;
                                        }
                                      });
                                    },
                                    colors: [
                                      Color(0xff0101ea),
                                      Color(0xff0101ea)
                                    ]),
                                // value: carNumber.value,
                                onChanged: (v) {
                                  carNumber.value = v;
                                })),

                        Visibility(
                            visible: deliverType.value == '0',
                            child: buildInput(
                                required: true,
                                title: "送货司机",
                                // value: carNumber.value,
                                onChanged: (v) {
                                  driverName.value = v;
                                })),

                        Visibility(
                            visible: deliverType.value == '0',
                            child: buildInput(
                                required: true,
                                title: "司机电话",
                                // value: carNumber.value,
                                onChanged: (v) {
                                  driverPhone.value = v;
                                })),

                        buildInput(
                            title: "物流备注",
                            value: remark.value,
                            onChanged: (v) {
                              remark.value = v;
                            }),

                        // Text(showText(attrVoList.value)),

                        ...attrVoList.value.asMap().keys.map((i) {
                          return Column(
                            children: [
                              buildInput(
                                  required: true,
                                  height: 120,
                                  labelHeight: 50,
                                  titleAfterSlot: Row(
                                    children: [
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Text(
                                        attrVoList.value[i]["attrName"],
                                        style: TextStyle(
                                            // color: Color(0xff7e7e7e),
                                            fontSize: 16),
                                      )
                                    ],
                                  ),
                                  title: "胎码",
                                  value: tireSize.value,
                                  type: "textArea",
                                  direction: "ttb",
                                  inputFormatters: [
                                    FilteringTextInputFormatter.deny(
                                        RegExp(',')),
                                    FilteringTextInputFormatter.deny(
                                        RegExp('，'))
                                  ],
                                  placeholder: "请输入胎码",
                                  onChanged: (v) {
                                    attrVoList.value[i]["tireSize"] = v;
                                    // tireSizes.value[i] = v;
                                    // state.tireSize.value = v;
                                  })
                            ],
                          );
                        }).toList(),

                        //新逻辑
                        Visibility(
                            visible: goodsList.isNotEmpty,
                            child: Column(children: [
                              ...newList.value.asMap().keys.map((i) {
                                return Container(
                                  width: double.infinity,
                                  // height: 70,
                                  child: Column(
                                    children: [
                                      Container(
                                          width: double.infinity,
                                          height: 70,
                                          child: Row(
                                            children: [
                                              Container(
                                                width: 70,
                                                height: double.infinity,
                                                // color: Colors.yellow,
                                                child: buildImage(
                                                    type: "ClipRect",
                                                    url: showText(newList[i]
                                                        ["skuPicUrl"])),
                                              ),
                                              Expanded(
                                                  child: Container(
                                                width: double.infinity,
                                                height: double.infinity,
                                                padding: EdgeInsets.only(
                                                    left: 10, top: 10),
                                                // color: Colors.blue,
                                                child: Text(showText(
                                                    newList[i]["productName"])),
                                              )),
                                              Container(
                                                width: 70,
                                                height: double.infinity,
                                                padding: EdgeInsets.only(
                                                    top: 10, right: 10),
                                                alignment: Alignment.topRight,
                                                // color: Colors.green,
                                                child: Text(
                                                  "x" +
                                                      showText(newList[i]
                                                          ["quantity"]),
                                                  style: TextStyle(
                                                      color: Colors.red),
                                                ),
                                              )
                                            ],
                                          )),
                                      Container(
                                        width: double.infinity,
                                        child: Column(
                                          children: [
                                            ...(newList[i]["tire"] as List)
                                                .asMap()
                                                .keys
                                                .map((j) {
                                              return buildInput(
                                                  required: true,
                                                  title: "胎码",
                                                  placeholder: "请输入胎码",
                                                  value: newList.value[i]
                                                      ["tire"][j],
                                                  inputFormatters: [
                                                    FilteringTextInputFormatter
                                                        .deny(RegExp(',')),
                                                    FilteringTextInputFormatter
                                                        .deny(RegExp('，'))
                                                  ],
                                                  onChanged: (v) {
                                                    newList.value[i]["tire"]
                                                        [j] = v;
                                                    print("数据===");
                                                    print(newList.value);
                                                    // list.value[i] = v;
                                                  });
                                            }).toList(),
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                  // Text(showText(newList[i]["productName"])),
                                  // color: Colors.red,
                                );
                              }).toList(),
                            ])),

                        // Text(showText(mySelectListPre.value)),
                      ],
                    )),
                  )),
                  Container(
                    width: double.infinity,
                    height: 80,
                    color: Colors.white,
                    child: Row(
                      children: [
                        // Expanded(
                        //   child: Container(
                        //     width: double.infinity,
                        //     height: double.infinity,
                        //     color: Colors.white,
                        //     padding: EdgeInsets.only(left: 15),
                        //     child: Column(
                        //       mainAxisAlignment: MainAxisAlignment.center,
                        //       children: [
                        //         Row(
                        //           children: [
                        //             Text(
                        //               "合计 ",
                        //               style: TextStyle(fontSize: 18),
                        //             ),
                        //             Text(
                        //               "¥",
                        //               style: TextStyle(
                        //                   color: Colors.red,
                        //                   fontSize: 16,
                        //                   fontWeight: FontWeight.bold),
                        //             ),
                        //             Text(
                        //               showText("000"),
                        //               style: TextStyle(
                        //                   fontSize: 20,
                        //                   fontWeight: FontWeight.bold,
                        //                   color: Colors.red),
                        //             )
                        //           ],
                        //         )
                        //       ],
                        //     ),
                        //   ),
                        // ),
                        Expanded(
                            child: Container(
                          width: double.infinity,
                          height: double.infinity,
                          color: Colors.white,
                          padding: EdgeInsets.only(
                              top: 10, bottom: 10, left: 10, right: 10),
                          child: buildButton(
                              title: "确定",
                              onClick: () async {
                                var _logisticCompany = logisticCompany.value;
                                var _logisticCompanySn =
                                    logisticCompanySn.value;
                                var _logisticNumber = logisticNumber.value;
                                var _tireSizes = tireSizes.value;
                                var _remark = remark.value;

                                var _deliverType = deliverType.value;
                                var _carNumber = carNumber.value;
                                var _driverName = driverName.value;
                                var _driverPhone = driverPhone.value;
                                var _newLogisticsCompany =
                                    newLogisticsCompany.value;

                                var attrVO = [];

                                if (_deliverType == "") {
                                  EasyLoading.showToast("请选择配送方式");
                                  return;
                                }
                                if (_deliverType == '0') {
                                  if (_carNumber == "") {
                                    EasyLoading.showToast("请填写送货车牌");
                                    return;
                                  }
                                  if (_driverName == "") {
                                    EasyLoading.showToast("请填写送货司机");
                                    return;
                                  }
                                  if (_driverPhone == "") {
                                    EasyLoading.showToast("请填写司机电话");
                                    return;
                                  }
                                }
                                if (_deliverType == '1') {
                                  if (_logisticCompany.isEmpty) {
                                    EasyLoading.showToast("填写物流公司");
                                    return;
                                  }
                                  if (_logisticNumber == "") {
                                    EasyLoading.showToast("请填写物流单号");
                                    return;
                                  }
                                  if (_driverPhone == '') {
                                    EasyLoading.showToast("请填写物流电话");
                                    return;
                                  }
                                }

                                for (var i = 0; i < attrVoList.length; i++) {
                                  if (attrVoList.value[i]["tireSize"] == "" ||
                                      attrVoList.value[i]["tireSize"] == null) {
                                    EasyLoading.showToast("请填写胎码");
                                    return;
                                  }
                                }

                                //新的逻辑
                                if (newList.isNotEmpty) {
                                  var index =
                                      newList.value.indexWhere((element) {
                                    var tire = element["tire"] as List;
                                    var i = tire.indexWhere((el) => el == "");
                                    return i != -1;
                                  });
                                  if (index != -1) {
                                    EasyLoading.showToast("请输入胎码");
                                    return;
                                  }

                                  // if (onSubmit != null) {

                                  //处理数据
                                  for (var k = 0;
                                      k < newList.value.length;
                                      k++) {
                                    var tire = newList.value[k]["tire"] as List;
                                    for (var h = 0; h < tire.length; h++) {
                                      var i = attrVO.indexWhere((element) =>
                                          element["orderSn"] ==
                                          newList[k]["orderSn"]);
                                      if (i != -1) {
                                        attrVO[i]["tire"] += ',' + tire[h];
                                      } else {
                                        attrVO.add({
                                          "orderSn": newList[k]["orderSn"],
                                          "tireSize": tire[h]
                                        });
                                      }
                                    }
                                  }

                                  print("翻译后的数据===");
                                  print(attrVO);
                                  // return;

                                  // onSubmit(res);
                                  // }
                                }
                                // var index = attrVoList.value.indexWhere(
                                //     (element) =>
                                //         element["tireSize"] == "" ||
                                //         element["tireSize"] == "null" ||
                                //         element["tireSize"] == null);
                                // if (index != 1) {
                                //   EasyLoading.showToast("请填写胎码");
                                //   return;
                                // }

                                print(attrVoList.value);

                                // EasyLoading.showToast("提交");

                                if (doUpdatelogistic != null) {
                                  var res = await doUpdatelogistic(
                                      deliverType: _deliverType,
                                      carNumber: _carNumber,
                                      driverName: _driverName,
                                      driverPhone: _driverPhone,
                                      newLogisticsCompany: _newLogisticsCompany,
                                      logisticCompany: _logisticCompany,
                                      // logisticCompanySn:
                                      //     _logisticCompanySn.join(","),
                                      logisticNumber: _logisticNumber,
                                      attrVo: attrVO,
                                      // tireSize: tireSizes.join(","),
                                      orderNo: type == "SH"
                                          ? showText(item["refundOrderNo"])
                                          : showText(item["orderNo"]),
                                      remark: remark.value);

                                  Get.back();
                                  EasyLoading.showToast("发货成功");
                                  Future.delayed(Duration(milliseconds: 500),
                                      () {
                                    if (onRefresh != null) {
                                      onRefresh();
                                    }
                                    //重新获取数据
                                    // handleSelectDetailById();
                                  });
                                  // onSubmit({
                                  //        logisticCompany: logisticCompany,
                                  //   logisticCompanySn:
                                  //       logisticCompanySn.join(","),
                                  //   logisticNumber: logisticNumber,
                                  //   tireSize: tireSizes.join(","),
                                  //   orderSn: orderSn,
                                  //   remark: remark
                                  // });
                                }
                                // if (tireSizes.isNotEmpty) {
                                //   var index = tireSizes
                                //       .indexWhere((element) => element.isEmpty);
                                //   if (index != -1) {
                                //     EasyLoading.showToast("请填写胎码");

                                //     return;
                                //   }
                                // }

                                // var res = await doUpdatelogistic(
                                //     logisticCompany: logisticCompany,
                                //     logisticCompanySn:
                                //         logisticCompanySn.join(","),
                                //     logisticNumber: logisticNumber,
                                //     tireSize: tireSizes.join(","),
                                //     orderSn: orderSn,
                                //     remark: remark);
                                // Get.back();
                                // EasyLoading.showToast("发货成功");
                                // Future.delayed(Duration(milliseconds: 500), () {
                                //   onRefresh();
                                //   //重新获取数据
                                //   // handleSelectDetailById();
                                // });
                                // if (submitFn != null) {
                                //   submitFn(mySelectListPre.value);
                                //   Get.back();
                                // }
                                // handleVisitorSeviceSubmit();
                                // Get.back();
                              },
                              colors: [Color(0xff0000f4), Color(0xff0000f4)]),
                        ))
                      ],
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    height: screenBottomHeight,
                  )
                ],
              )))));
}
